package cn.nexttec.noteplayer.ui.activities

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import cn.nexttec.noteplayer.R
import cn.nexttec.noteplayer.common.Preference
import cn.nexttec.noteplayer.databinding.ActivityImageEditorBinding
import cn.nexttec.noteplayer.ui.widget.image_editor.ImageEditorView
import com.bumptech.glide.Glide
import dagger.hilt.android.AndroidEntryPoint
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import javax.inject.Inject
import javax.inject.Named

@AndroidEntryPoint
class ImageEditorActivity : AppCompatActivity() {

    @Inject lateinit var preference: Preference
    @Inject @Named("TempDir") lateinit var tempDir:File
    private lateinit var _binding:ActivityImageEditorBinding
    private lateinit var imagePath:String
    private val binding get() = _binding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = ActivityImageEditorBinding.inflate(layoutInflater)
        setContentView(binding.root)
        window.statusBarColor = Color.BLACK
        imagePath = intent.getStringExtra("image")?:""
    }

    override fun onResume() {
        super.onResume()
        val inputStream = FileInputStream(File(imagePath))
        binding.imageEditor.setImage(inputStream)
        binding.imageEditor.setOnImageSavedListener(object :ImageEditorView.OnImageSavedListener{
            override fun onImageSaved(result: Bitmap) {
                //        // 保存到文件（可选）
                val outputFile = File(
                    tempDir,
                    "edited_${System.currentTimeMillis()}.jpg"
                )
                FileOutputStream(outputFile).use {
                    result.compress(Bitmap.CompressFormat.JPEG, 90, it)
                }

                val returenIntent = Intent().apply {
                    putExtra("image", outputFile.absolutePath)
                }
                setResult(RESULT_OK, returenIntent)
                this@ImageEditorActivity.finish()
            }
        })
    }
}